package com.konsung.provide;

import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.text.TextUtils;

import com.konsung.bean.MeasureDataBean;
import com.konsung.bean.PatientBean;
import com.konsung.greendaoUtil.DBUtitl;
import com.konsung.greendaoUtil.GreenDaoManager;
import com.konsung.greendaoUtil.MeasureDataBeanDao;
import com.konsung.greendaoUtil.PatientBeanDao;
import com.konsung.util.IdCardUtil;
import com.konsung.util.JsonUtil;
import com.konsung.util.SpUtils;
import com.konsung.util.constant.GlobalConstant;

import org.greenrobot.greendao.query.WhereCondition;

import java.util.Date;
import java.util.List;

/**
 * 公卫数据内容提供
 */

public class PHDataProvider extends ExtraProvider {
    @Override
    Uri insertCitizen(Uri uri, ContentValues values) {
        // 姓名
        String name = values.containsKey("name") ? values.getAsString("name") : "";
        // 身份证,为了查询方便，如果没有身份证，公卫会传-1过来
        String idcard = values.containsKey("idcard") ? values.getAsString("idcard") : "-1";
        // 会员卡,为了查询方便，如果没有会员卡，公卫会传-1过来,8600暂不支持会员卡
        String clinicCardNumber = values.containsKey("clinicCardNumber") ?
                values.getAsString("clinicCardNumber") : "-1";
        // 年龄，如果没有设置年龄，公卫会传-1过来
        String age = values.containsKey("age") ? values.getAsString("age") : "-1";
        // 性别
        String gender = values.containsKey("gender") ? values.getAsString("gender") : "0";
        // 体重
        String weight = values.containsKey("weight") ? values.getAsString("weight") : "0";
        // 身高
        String height = values.containsKey("height") ? values.getAsString("height") : "0";
        // 血型
        String blood = values.containsKey("blood") ? values.getAsString("blood") : "4";
        String phone = values.containsKey("phone") ? values.getAsString("phone") : "";
        String address = values.containsKey("address") ? values.getAsString("address") : "";
        // 多应用的身份证字段是card, idcard是uuid,使用like查询不区分大小写
        WhereCondition idCardCondition = PatientBeanDao.Properties.Idcard.like(idcard);
        // 暂不支持会员卡
        //WhereCondition clinicCondition = PatientBeanDao.Properties.
        //     MemberShipCard.eq(clinicCardNumber);
        List<PatientBean> list = GreenDaoManager.getInstance(getContext()).getSession()
                .getPatientBeanDao().queryBuilder()
                .where(idCardCondition).list();
        Uri result;
        if (list.size() > 0 && idcard.length() == 18) {
            // 已经存在
            result = ContentUris.withAppendedId(uri, -1);
        } else {
            PatientBean bean = new PatientBean();
            bean.setName(name);
            if (!idcard.equals("-1")) {
                bean.setIdcard(idcard);
            }
            // 暂不支持会员卡
            // if (!clinicCardNumber.equals("-1")) {
            //     bean.setMemberShipCard(clinicCardNumber);
            // }
            Date date = IdCardUtil.getAgeForIdCard(idcard);
            bean.setBirthday(date.getTime());
            if ("-1".equals(age)) {
                bean.setAge(IdCardUtil.getAge(date));
            } else {
                try {
                    bean.setAge(Integer.valueOf(age));
                } catch (Exception e) {
                    e.printStackTrace();
                    bean.setAge(0);
                }
            }
            bean.setWeight(Float.valueOf(weight));
            bean.setHeight(Float.valueOf(height));
            bean.setContact(phone);
            bean.setAddress(address);
            try {
                bean.setSex(Integer.valueOf(gender));
            } catch (Exception e) {
                e.printStackTrace();
                bean.setSex(0);
            }
            bean.setBlood(ServiceProvider.convertBlood(blood));
            PatientBeanDao patientDao = GreenDaoManager.getPatientDao(getContext());
            long id = patientDao.insertOrReplace(bean);
            result = ContentUris.withAppendedId(uri, id);
        }
        return result;
    }

    @Override
    Cursor queryCurrentCitizen(MatrixCursor cursor) {
        try {
            String currentPatient = "";
            PatientBean patientBean = DBUtitl.getCurrentPatient(getContext());
            if (patientBean != null) {

                currentPatient = JsonUtil.toJson(patientBean);
            }
            cursor.addRow(new Object[]{currentPatient});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cursor;
    }

    @Override
    Cursor queryCurrentMeasureData(MatrixCursor cursor) {
        try {
            MeasureDataBeanDao measureDataDao = GreenDaoManager
                    .getMeasureDao(getContext());
            String uuid = SpUtils.getSp(getContext(), GlobalConstant.APP_CONFIG,
                    GlobalConstant.CURRENT_PATIENT, "");
            MeasureDataBean measureDataBean = null;
            if (!TextUtils.isEmpty(uuid)) {
                //测量时间倒叙，身份证相同
                List<MeasureDataBean> query = measureDataDao.queryBuilder()
                        .orderDesc(MeasureDataBeanDao.Properties.MeasureTime)
                        .where(MeasureDataBeanDao.Properties.Idcard.eq(uuid))
                        .build()
                        .forCurrentThread()
                        .list();
                if (query != null && query.size() > 0) {
                    measureDataBean = query.get(0);
                }
            }

            String data;
            if (measureDataBean == null) {
                data = "";
            } else {
                data = JsonUtil.toJson(measureDataBean);
            }
            cursor.addRow(new Object[]{data});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cursor;
    }

    @Override
    Cursor queryCurrentUser(MatrixCursor cursor) {
        // 应用启动管理提供，健康档案无需实现
        return null;
    }

    @Override
    Cursor queryIpAddress(MatrixCursor cursor) {
        // 软件设置提供，健康档案无需实现
        return null;
    }

    @Override
    String getVersion() {
        return "1";
    }
}
